#!/usr/bin/env python3
"""
用户Pydantic模式
"""

from datetime import datetime


from pydantic import BaseModel, EmailStr, Field, field_validator


class UserBase(BaseModel):
    """用户基础模式"""
    username: str = Field(..., min_length=3, max_length=50, description="用户名")
    name: str = Field(..., min_length=2, max_length=100, description="姓名")
    email: EmailStr | None = Field(None, description="邮箱")
    phone: str | None = Field(None, max_length=20, description="手机号")


class UserCreate(UserBase):
    """用户创建模式"""
    password: str = Field(..., min_length=6, max_length=20, description="密码")
    role: str = Field("guard", description="用户角色")

    @field_validator('role')
    def validate_role(cls, v: str) -> str:
        if v not in ['guard', 'admin', 'super-admin']:
            raise ValueError('角色必须是 guard、admin 或 super-admin')
        return v


class UserUpdate(UserBase):
    """用户更新模式"""
    password: str | None = Field(None, min_length=6, max_length=20, description="新密码")
    role: str | None = Field(None, description="用户角色")
    is_active: bool | None = Field(None, description="是否激活")

    @field_validator('role')
    def validate_role(cls, v: str | None) -> str | None:
        if v and v not in ['guard', 'admin', 'super-admin']:
            raise ValueError('角色必须是 guard、admin 或 super-admin')
        return v


class UserLogin(BaseModel):
    """用户登录模式"""
    username: str = Field(..., description="用户名")
    password: str = Field(..., description="密码")


class UserResponse(UserBase):
    """用户响应模式"""
    id: int = Field(..., description="用户ID")
    role: str = Field(..., description="用户角色")
    is_active: bool = Field(..., description="是否激活")
    last_login: datetime | None = Field(None, description="最后登录时间")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="更新时间")

    class Config:
        from_attributes = True


class TokenResponse(BaseModel):
    """令牌响应模式"""
    access_token: str = Field(..., description="访问令牌")
    token_type: str = Field("bearer", description="令牌类型")
    user: UserResponse = Field(..., description="用户信息")